<?php
/**
 * Password Reminder page controller
 *
 * @author Dima
 *
 */

class ForgotController extends modules_default_controllers_ControllerBase
{
//----------------------------------------------------------------------------------------------------

	protected $_bForLoggedUsersOnly = false;

	public $ajaxable = array(
		'index' => array('json'),
	);

//----------------------------------------------------------------------------------------------------

	public function init()
	{
		if (! $this->getRequest()->isXmlHttpRequest())
		{
			parent::init();
			$this->view->title = 'Password reminder';
			$this->view->headLink()->appendStylesheet('/css/validation_css/screen.css');
			$this->view->headScript()->appendFile('/js/jquery.validate.js');

			$this->view->headScript()->appendFile('/js/forgot.js');

		}

		$this->_helper->AjaxContext()->initContext('json');
	}

//----------------------------------------------------------------------------------------------------

	/**
	 * Default action
	 *
	 */
	public function indexAction()
	{
		$oRequest = $this->getRequest();
		$oForm = new modules_default_forms_ForgotForm();

		$aInfoMessages = array();
		$aErrorMessages = array();

		if ($this->getRequest()->isPost())
		{
			if ($oForm->isValid($oRequest->getPost()))
			{
				/*
				 * get users data and send password to this email
				 */
				$oUser = models_UserMapper::findByEmail( $oForm->getValue('email') );
//				print_r($oUser);
				$sBody = "\n\n" . 'Your rassword: ' . $oUser->password;
				$sToAddress = $oUser->email;
				$sToName = $oUser->firstName . $oUser->lastName;
				$sSubject = 'Password reminder';
//				$forgotKey = substr(md5(time()), 0, 8);

//				models_UserMapper::updateUser($oUser->id, 'forgot_key', $forgotKey);
				$url = $_SERVER["HTTP_HOST"];

				$body = "
Hello, " . $oUser->firstName . " " . $oUser->lastName . "!
You have just requested your forgotten password on ".$url."\n\n".
$sBody. "\n\n

Regards,
Qukkie
";


				lemar_User::send($body, $oForm->getValue('email'), $sSubject, lemar_User::LOG_EMAIL_ADMIN);
				$this->_redirect('/login/');
/*
				if( true === Lemar_Mailer::sendFromSite($sBody, $sToAddress, $sToName, $sSubject) )
				{
					$aInfoMessages[0][0] = "#email"; // FIELDID
					$aInfoMessages[0][1] = "Your password has been sent to your email address."; // TEXT ERROR
					$aInfoMessages[0][2] = 'pass'; // BOX COLOR
				}
				else
				{
					$aInfoMessages[0][0] = "#email"; // FIELDID
					$aInfoMessages[0][1] = "Sorry, we have some errors at the server. Please try again later."; // TEXT ERROR
					$aInfoMessages[0][2] = 'error'; // BOX COLOR
				}
*/
				$this->view->jsonValidateReturn = $aInfoMessages;
			}
			else
			{
				$aErrors = $oForm->getErrors();
				$aMessages = $oForm->getMessages();
				$iIndex = 0;
				foreach ($aErrors as $sControlName => $sErrorIndexes)
				{
					if (isset($sErrorIndexes[0]))
					{
						$aErrorMessages[$iIndex][] = '#'.$sControlName;
						$aErrorMessages[$iIndex][] = $aMessages[$sControlName][$sErrorIndexes[0]];
						$aErrorMessages[$iIndex][] = 'error';
						$iIndex++;
					}
				}

				$errorMessage = $aErrorMessages;
                foreach ($aErrorMessages as $sControlName => $sErrorIndexes)
                {
					$errorMessage[str_ireplace('#', '', $sErrorIndexes[0])] = $sErrorIndexes[1];
                }

				$oZendSession = Zend_Registry::getInstance()->get('Zend_Session_Namespace');
				$oZendSession->emailValidation = $aErrorMessages[0][1];

				$this->view->errorMessage = $errorMessage;
			}
		}
	}

//----------------------------------------------------------------------------------------------------

	public function keyAction()
	{
		$oRequest = $this->getRequest();
		$key  = $oRequest->getParam('key');
		if ($oRequest->isPost())
		{
			$newPassword = substr(md5(time()), 0, 8);
			$keyCount = models_UserMapper::updateForgotKey($key, 'password', $newPassword);
			if (0 != $keyCount)
			{
				$oUser = models_UserMapper::findByForgotKey($key);
				models_UserMapper::updateForgotKey($key, 'forgot_key', md5($newPassword.time()));
				$sToAddress = $oUser->email;
				$sToName = $oUser->firstName . $oUser->lastName;
				$sSubject = 'Password reminder';
				$url = $_SERVER["HTTP_HOST"];
				$body = "
Hello, " . $oUser->firstName . " " . $oUser->lastName . "!

A new password has been generated for you on HornedFrogDelivery.com. Here's your updated login information:

   email: 		$sToAddress
   Password:  	$newPassword\n\n

 We highly recommend to change your password after logging in. You can do it in your member area.

 Regards,
Horned Frog Delivery
";


				lemar_User::send($body, $oUser->email, $sSubject, lemar_User::LOG_EMAIL_ADMIN);
				$oZendSession = Zend_Registry::getInstance()->get('Zend_Session_Namespace');
				$oZendSession->errorMessage = '';

				$this->_redirect('/login/index/message/forgot');
			}
			else
			{
				$this->view->error = 'This key is not correct.';
			}
		}
		$oZendSession = Zend_Registry::getInstance()->get('Zend_Session_Namespace');
		if ($oZendSession->emailValidation)
		{
			$this->view->emailValidation =  $oZendSession->emailValidation;
			$oZendSession->emailValidation = '';
		}
		$this->view->key = $key ;
	}

//----------------------------------------------------------------------------------------------------
}